package com.example.partner.fragment.team;

import static com.example.partner.common.ConfigConstant.BASE_URL;

import android.content.Context;
import android.content.Intent;
import android.content.SharedPreferences;
import android.os.Bundle;
import android.provider.MediaStore;
import android.view.ContextThemeWrapper;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.Button;
import android.widget.LinearLayout;
import android.widget.TextView;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.lifecycle.ViewModelProvider;

import com.example.partner.R;
import com.example.partner.activity.team.UpdateTeamActivity;
import com.example.partner.common.BaseResponse;
import com.example.partner.common.TeamInfoViewModel;
import com.example.partner.model.request.DeleteRequest;
import com.example.partner.model.vo.TeamUserVo;
import com.example.partner.service.TeamService;
import com.google.android.flexbox.FlexboxLayout;

import org.json.JSONArray;
import org.json.JSONException;

import java.text.SimpleDateFormat;

import retrofit2.Call;
import retrofit2.Callback;
import retrofit2.Response;
import retrofit2.Retrofit;
import retrofit2.converter.gson.GsonConverterFactory;

public class TeamDetialFragment extends Fragment {
    private TeamService teamService;;
    TextView tvtname,tvtmaster,tvtnum,tvttime,tvtbuildtime,tvtplace,tvtstage;
    FlexboxLayout teamLable;
    private TeamInfoViewModel viewModel;
    Button btmodify,btdelete;
    Long userId,teamid,teamMasterId;
    TeamUserVo teamUserVo;
    DeleteRequest deleteRequest;
    LinearLayout btshow;


    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        // 加载布局文件
        return inflater.inflate(R.layout.fragment_team_detial, container, false);
    }

    @Override
    public void onViewCreated(@NonNull View view, @Nullable Bundle savedInstanceState) {
        super.onViewCreated(view, savedInstanceState);
        // 获取与 Fragment 关联的 Activity 的 SharedPreferences
        SharedPreferences sharedPreferences = getActivity().getSharedPreferences("CurrentUser", Context.MODE_PRIVATE);
        userId = sharedPreferences.getLong("userId", -1);
        // 在这里初始化 UI 组件
        tvtbuildtime = view.findViewById(R.id.tbuildtime);
        tvtmaster = view.findViewById(R.id.tmaster);
        tvtname = view.findViewById(R.id.tname);
        tvtnum = view.findViewById(R.id.tnum);
        tvtplace = view.findViewById(R.id.tplace);
        tvtstage = view.findViewById(R.id.tstage);
        tvttime = view.findViewById(R.id.ttime);
        teamLable = view.findViewById(R.id.teamLabel);
        btshow=view.findViewById(R.id.btshow);
        btmodify=view.findViewById(R.id.btModifyTeam);
        btdelete=view.findViewById(R.id.btDeleteTeam);
        // 初始化Retrofit
        Retrofit retrofit = new Retrofit.Builder()
                .baseUrl(BASE_URL) // 替换为您的服务器地址
                .addConverterFactory(GsonConverterFactory.create())
                .build();
        teamService = retrofit.create(TeamService.class);
        //获取与 Fragment 关联的 Activity 的viewModel
        viewModel = new ViewModelProvider(requireActivity()).get(TeamInfoViewModel.class);
        teamid = viewModel.getId();
        MatchTeam();
    }


    private void MatchTeam() {
        teamService.getTeamById(teamid).enqueue(new Callback<BaseResponse<TeamUserVo>>() {
            @Override
            public void onResponse(Call<BaseResponse<TeamUserVo>> call, Response<BaseResponse<TeamUserVo>> response) {
                if (response.isSuccessful() && response.body() != null) {
                    // 处理成功的响应
                    teamUserVo = response.body().getData();
                    if (teamUserVo == null){
                        Toast.makeText(getContext(), "不存在该队伍", Toast.LENGTH_SHORT).show();
                    }else {
                        SimpleDateFormat format = new SimpleDateFormat("yyyy-MM-dd");
                        String ExpireTime = format.format(teamUserVo.getExpireTime());
                        String BuildTime = format.format(teamUserVo.getCreateTime());
                        tvttime.setText(ExpireTime);
                        if(teamUserVo.getStatus().equals(0)){
                            tvtstage.setText("公开");
                        }
                        if(teamUserVo.getStatus().equals(1)){
                            tvtstage.setText("私有");
                        }
                        if(teamUserVo.getStatus().equals(2)){
                            tvtstage.setText("加密");
                        }
                        tvtplace.setText(teamUserVo.getPlace());
                        tvtnum.setText(teamUserVo.getHasJoinNum()+"/"+teamUserVo.getMaxNum());
                        tvtname.setText(teamUserVo.getName());
                        if(teamUserVo.getCreateUser()!=null){
                            tvtmaster.setText(teamUserVo.getCreateUser().getUsername());
                        }
                        tvtbuildtime.setText(BuildTime);
                        teamMasterId=teamUserVo.getUserId();
                        if(teamMasterId.equals(userId)){
                            btshow.setVisibility(View.VISIBLE);
                            btdelete.setOnClickListener(view -> deleteTeam());
                            btmodify.setOnClickListener(view -> modifyTeam());
                        }
                        String jsonString = teamUserVo.getTags();
                        try {
                            // 将JSON字符串转换为JSONArray
                            JSONArray jsonArray = new JSONArray(jsonString);

                            // 创建一个字符串数组来存储解析后的数据
                            String[] tagsArray = new String[jsonArray.length()];

                            // 遍历JSONArray，将每个元素添加到字符串数组中
                            for (int i = 0; i < jsonArray.length(); i++) {
                                tagsArray[i] = jsonArray.getString(i);
                            }
                            // 输出解析后的字符串数组
                            for (String tag : tagsArray) {
                                // 创建一个新的ContextThemeWrapper，传入当前的Context和您的样式资源
                                ContextThemeWrapper newContext = new ContextThemeWrapper(getContext(), R.style.TagStyle);

                                // 使用新的Context来创建一个TextView
                                TextView tagView = new TextView(newContext);
                                tagView.setText(tag);
                                // 设置TextView的其他属性，如margin，padding等
                                FlexboxLayout.LayoutParams layoutParams = new FlexboxLayout.LayoutParams(
                                        ViewGroup.LayoutParams.WRAP_CONTENT,
                                        ViewGroup.LayoutParams.WRAP_CONTENT);
                                layoutParams.setMargins(10, 5, 10, 5); // 根据需要设置margin值
                                tagView.setLayoutParams(layoutParams);

                                // 最后，将TextView添加到FlexboxLayout中
                                teamLable.addView(tagView);
                            }
                        } catch (JSONException e) {
                            e.printStackTrace();
                        }



                    }
                } else {
                    // 处理错误情况

                }
            }

            @Override
            public void onFailure(Call<BaseResponse<TeamUserVo>> call, Throwable t) {
                // 网络错误处理
                t.printStackTrace();
            }
        });
    }

    private void deleteTeam() {
        new android.app.AlertDialog.Builder(getActivity())
                .setTitle("删除队伍") // 设置对话框标题
                .setMessage("你真的要删除这个队伍吗？") // 设置要显示的消息
                .setPositiveButton("确定", (dialog, which) -> {
                    // 用户点击确定按钮后的操作
                    deleteRequest=new DeleteRequest();
                    deleteRequest.setId(teamid);
                    teamService.deleteTeam(deleteRequest).enqueue(new Callback<BaseResponse<Boolean>>() {
                        @Override
                        public void onResponse(Call<BaseResponse<Boolean>> call, Response<BaseResponse<Boolean>> response) {
                            if(response.isSuccessful()){

                            }
                        }
                        @Override
                        public void onFailure(Call<BaseResponse<Boolean>> call, Throwable t) {

                        }
                    });
                })
                .setNegativeButton("取消",(dialog, which) ->{
                })
                .show();

    }

    private void modifyTeam() {
        Intent updateIntent = new Intent(getActivity(), UpdateTeamActivity.class);
        updateIntent.putExtra("teamUserVo",teamUserVo);
        getActivity().startActivity(updateIntent);
    }




}
